package services

import (
	"context"
	"fmt"
	"strings"
	"time"

	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/hlPay/models"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/common"
	"gorm.io/gorm"
)

// CardholderService HlPay持卡人服务
type CardholderService struct {
	db *gorm.DB
}

// NewCardholderService 创建持卡人服务实例
func NewCardholderService(db *gorm.DB) *CardholderService {
	return &CardholderService{
		db: db,
	}
}

// generateHlPayCardholderID 生成HlPay持卡人ID
// 格式：HL + 时间戳 + 4位随机数
func (s *CardholderService) generateHlPayCardholderID() string {
	// 获取当前时间戳（毫秒）
	timestamp := time.Now().UnixNano() / int64(time.Millisecond)

	// 生成4位随机数（这里使用时间戳的最后4位作为简单实现）
	randomNum := timestamp % 10000

	// 组合成持卡人ID：HL + 时间戳 + 4位随机数
	cardholderID := fmt.Sprintf("HL%d%04d", timestamp, randomNum)

	return cardholderID
}

// CreateCardholder 创建持卡人
func (s *CardholderService) CreateCardholder(ctx context.Context, req *models.CreateHlPayCardholderRequest) (*models.HlPayCardholderResponse, error) {
	// 开启事务
	tx := s.db.WithContext(ctx).Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 验证字段不包含中文
	if err := common.ValidateCardholderFieldsNoChinese(
		req.FirstName,
		req.LastName,
		req.Email,
		req.Mobile,
		req.ResidentialAddress,
		req.ResidentialCity,
		req.ResidentialState,
		req.ResidentialPostalCode,
	); err != nil {
		tx.Rollback()
		return nil, err
	}

	// 生成HlPay持卡人ID
	hlpayCardholderID := s.generateHlPayCardholderID()

	// 检查 hlpay_cardholder_id 是否已存在（确保唯一性）
	var existingCardholder models.HlPayCardholder
	if err := tx.Where("hlpay_cardholder_id = ?", hlpayCardholderID).First(&existingCardholder).Error; err == nil {
		tx.Rollback()
		return nil, fmt.Errorf("持卡人ID已存在，请重试")
	}

	// 注意：移除了用户唯一性检查，允许一个用户创建多个持卡人
	// 注意：移除了邮箱和手机号唯一性检查，允许重复的联系方式

	// 解析出生日期
	var dateOfBirth *time.Time
	if req.DateOfBirth != "" {
		if parsed, err := time.Parse("2006-01-02", req.DateOfBirth); err == nil {
			dateOfBirth = &parsed
		}
	}

	// 创建持卡人
	cardholder := &models.HlPayCardholder{
		UserID:                     req.UserID,
		HlPayCardholderID:          hlpayCardholderID, // 设置生成的持卡人ID
		FirstName:                  req.FirstName,
		LastName:                   req.LastName,
		CardholderNameAbbreviation: req.CardholderNameAbbreviation,
		Email:                      req.Email,
		Mobile:                     req.Mobile,
		MobilePrefix:               req.MobilePrefix,
		DateOfBirth:                dateOfBirth,
		CertType:                   req.CertType,
		Portrait:                   req.Portrait,
		ReverseSide:                req.ReverseSide,
		NationalityCountryCode:     req.NationalityCountryCode,
		ResidentialAddress:         req.ResidentialAddress,
		ResidentialCity:            req.ResidentialCity,
		ResidentialCountryCode:     req.ResidentialCountryCode,
		ResidentialPostalCode:      req.ResidentialPostalCode,
		ResidentialState:           req.ResidentialState,
		Status:                     "ACTIVE", // 使用ACTIVE状态，在返回时映射为normal
		CreatedAt:                  time.Now(),
		UpdatedAt:                  time.Now(),
		MatrixAccount:              req.MatrixAccount,
		MemberID:                   req.MemberID,
		IsLegal:                    "N",
		CardholderReviewStatus:     "cert_required",
		Reason:                     "",
	}

	if err := tx.Create(cardholder).Error; err != nil {
		tx.Rollback()
		return nil, fmt.Errorf("创建持卡人失败: %v", err)
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		return nil, fmt.Errorf("提交事务失败: %v", err)
	}

	// 返回持卡人详情
	return s.GetCardholderDetail(ctx, cardholder.ID)
}

// GetCardholderDetail 获取持卡人详情
func (s *CardholderService) GetCardholderDetail(ctx context.Context, cardholderID int64) (*models.HlPayCardholderResponse, error) {
	var cardholder models.HlPayCardholder
	if err := s.db.WithContext(ctx).Where("id = ?", cardholderID).First(&cardholder).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("持卡人不存在")
		}
		return nil, fmt.Errorf("查询持卡人失败: %v", err)
	}

	// 构建响应
	response := &models.HlPayCardholderResponse{
		ID:                         cardholder.ID,
		UserID:                     cardholder.UserID,
		HlPayCardholderID:          cardholder.HlPayCardholderID,
		FirstName:                  cardholder.FirstName,
		LastName:                   cardholder.LastName,
		CardholderNameAbbreviation: cardholder.CardholderNameAbbreviation,
		Email:                      cardholder.Email,
		Mobile:                     cardholder.Mobile,
		MobilePrefix:               cardholder.MobilePrefix,
		DateOfBirth:                cardholder.DateOfBirth,
		CertType:                   cardholder.CertType,
		Portrait:                   cardholder.Portrait,
		ReverseSide:                cardholder.ReverseSide,
		NationalityCountryCode:     cardholder.NationalityCountryCode,
		ResidentialAddress:         cardholder.ResidentialAddress,
		ResidentialCity:            cardholder.ResidentialCity,
		ResidentialCountryCode:     cardholder.ResidentialCountryCode,
		ResidentialPostalCode:      cardholder.ResidentialPostalCode,
		ResidentialState:           cardholder.ResidentialState,
		Status:                     cardholder.Status,
		CreatedAt:                  cardholder.CreatedAt,
		UpdatedAt:                  cardholder.UpdatedAt,
		MatrixAccount:              cardholder.MatrixAccount,
		MemberID:                   cardholder.MemberID,
		IsLegal:                    cardholder.IsLegal,
		CardholderReviewStatus:     cardholder.CardholderReviewStatus,
		Reason:                     cardholder.Reason,
	}

	return response, nil
}

// GetCardholderByUserID 根据用户ID获取持卡人（返回第一个）
func (s *CardholderService) GetCardholderByUserID(ctx context.Context, userID int64) (*models.HlPayCardholderResponse, error) {
	var cardholder models.HlPayCardholder
	if err := s.db.WithContext(ctx).Where("user_id = ?", userID).First(&cardholder).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("持卡人不存在")
		}
		return nil, fmt.Errorf("查询持卡人失败: %v", err)
	}

	return s.GetCardholderDetail(ctx, cardholder.ID)
}

// GetCardholdersByUserID 根据用户ID获取所有持卡人
func (s *CardholderService) GetCardholdersByUserID(ctx context.Context, userID int64) ([]*models.HlPayCardholderResponse, error) {
	var cardholders []models.HlPayCardholder
	if err := s.db.WithContext(ctx).Where("user_id = ?", userID).Order("created_at DESC").Find(&cardholders).Error; err != nil {
		return nil, fmt.Errorf("查询持卡人失败: %v", err)
	}

	// 构建响应列表
	var responses []*models.HlPayCardholderResponse
	for _, cardholder := range cardholders {
		response := &models.HlPayCardholderResponse{
			ID:                         cardholder.ID,
			UserID:                     cardholder.UserID,
			HlPayCardholderID:          cardholder.HlPayCardholderID,
			FirstName:                  cardholder.FirstName,
			LastName:                   cardholder.LastName,
			CardholderNameAbbreviation: cardholder.CardholderNameAbbreviation,
			Email:                      cardholder.Email,
			Mobile:                     cardholder.Mobile,
			MobilePrefix:               cardholder.MobilePrefix,
			DateOfBirth:                cardholder.DateOfBirth,
			CertType:                   cardholder.CertType,
			Portrait:                   cardholder.Portrait,
			ReverseSide:                cardholder.ReverseSide,
			NationalityCountryCode:     cardholder.NationalityCountryCode,
			ResidentialAddress:         cardholder.ResidentialAddress,
			ResidentialCity:            cardholder.ResidentialCity,
			ResidentialCountryCode:     cardholder.ResidentialCountryCode,
			ResidentialPostalCode:      cardholder.ResidentialPostalCode,
			ResidentialState:           cardholder.ResidentialState,
			Status:                     cardholder.Status,
			CreatedAt:                  cardholder.CreatedAt,
			UpdatedAt:                  cardholder.UpdatedAt,
			MatrixAccount:              cardholder.MatrixAccount,
			MemberID:                   cardholder.MemberID,
			IsLegal:                    cardholder.IsLegal,
			CardholderReviewStatus:     cardholder.CardholderReviewStatus,
			Reason:                     cardholder.Reason,
		}
		responses = append(responses, response)
	}

	return responses, nil
}

// GetCardholderList 获取持卡人列表
func (s *CardholderService) GetCardholderList(ctx context.Context, pageIndex, pageSize int, filters map[string]interface{}) ([]*models.HlPayCardholderResponse, int64, error) {
	query := s.db.WithContext(ctx).Model(&models.HlPayCardholder{})

	// 添加查询条件
	if firstName, ok := filters["first_name"].(string); ok && firstName != "" {
		query = query.Where("first_name LIKE ?", "%"+firstName+"%")
	}
	if lastName, ok := filters["last_name"].(string); ok && lastName != "" {
		query = query.Where("last_name LIKE ?", "%"+lastName+"%")
	}
	if email, ok := filters["email"].(string); ok && email != "" {
		query = query.Where("email LIKE ?", "%"+email+"%")
	}
	if mobile, ok := filters["mobile"].(string); ok && mobile != "" {
		query = query.Where("mobile LIKE ?", "%"+mobile+"%")
	}
	if status, ok := filters["status"].(string); ok && status != "" {
		query = query.Where("status = ?", status)
	}
	if userID, ok := filters["user_id"].(int64); ok && userID > 0 {
		query = query.Where("user_id = ?", userID)
	}

	// 新增查询条件：持卡人ID
	if cardholderID, ok := filters["cardholder_id"].(string); ok && cardholderID != "" {
		query = query.Where("hlpay_cardholder_id = ?", cardholderID)
	}

	// 新增查询条件：创建时间范围
	if createdAtStart, ok := filters["created_at_start"].(string); ok && createdAtStart != "" {
		query = query.Where("created_at >= ?", createdAtStart)
	}
	if createdAtEnd, ok := filters["created_at_end"].(string); ok && createdAtEnd != "" {
		query = query.Where("created_at <= ?", createdAtEnd)
	}

	// 新增查询条件：姓名模糊查询（支持firstName和lastName）
	if name, ok := filters["name"].(string); ok && name != "" {
		// 检查是否包含 / 分割符
		if strings.Contains(name, "/") {
			// 使用 / 分割姓名
			parts := strings.Split(name, "/")
			if len(parts) == 2 {
				searchFirstName := strings.TrimSpace(strings.ToUpper(parts[0]))
				searchLastName := strings.TrimSpace(strings.ToUpper(parts[1]))

				// 构建精确的姓名匹配查询
				query = query.Where(`
					(
						(first_name LIKE ? AND last_name LIKE ?) OR
						(first_name LIKE ? AND last_name LIKE ?)
					)
				`,
					"%"+searchFirstName+"%", "%"+searchLastName+"%",
					"%"+searchLastName+"%", "%"+searchFirstName+"%")
			} else {
				// 分割后不是2个部分，使用模糊匹配
				query = query.Where("(first_name LIKE ? OR last_name LIKE ?)", "%"+name+"%", "%"+name+"%")
			}
		} else {
			// 没有 / 分割符，使用原来的模糊匹配逻辑
			query = query.Where(`
				(first_name LIKE ? OR last_name LIKE ?) OR
				(CONCAT(first_name, last_name) LIKE ?) OR
				(CONCAT(last_name, first_name) LIKE ?)
			`,
				"%"+name+"%", "%"+name+"%",
				"%"+name+"%", "%"+name+"%")
		}
	}

	// 新增查询条件：firstName精确查询
	if firstName, ok := filters["first_name"].(string); ok && firstName != "" {
		query = query.Where("first_name LIKE ?", "%"+firstName+"%")
	}

	// 新增查询条件：lastName精确查询
	if lastName, ok := filters["last_name"].(string); ok && lastName != "" {
		query = query.Where("last_name LIKE ?", "%"+lastName+"%")
	}

	// 新增查询条件：矩阵账户
	if matrixAccount, ok := filters["matrix_account"].(string); ok && matrixAccount != "" {
		query = query.Where("matrix_account = ?", matrixAccount)
	}

	// 统计总数
	var total int64
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, fmt.Errorf("统计持卡人数量失败: %v", err)
	}

	// 分页查询
	var cardholders []models.HlPayCardholder
	offset := (pageIndex - 1) * pageSize
	if err := query.Offset(int(offset)).Limit(int(pageSize)).Order("created_at DESC").Find(&cardholders).Error; err != nil {
		return nil, 0, fmt.Errorf("查询持卡人列表失败: %v", err)
	}

	// 构建响应列表
	var responses []*models.HlPayCardholderResponse
	for _, cardholder := range cardholders {
		// 将平台状态映射为统一状态
		unifiedStatus := common.MapPlatformCardholderStatusToUnified("hlpay", cardholder.Status)
		response := &models.HlPayCardholderResponse{
			ID:                         cardholder.ID,
			UserID:                     cardholder.UserID,
			HlPayCardholderID:          cardholder.HlPayCardholderID,
			FirstName:                  cardholder.FirstName,
			LastName:                   cardholder.LastName,
			CardholderNameAbbreviation: cardholder.CardholderNameAbbreviation,
			Email:                      cardholder.Email,
			Mobile:                     cardholder.Mobile,
			MobilePrefix:               cardholder.MobilePrefix,
			DateOfBirth:                cardholder.DateOfBirth,
			CertType:                   cardholder.CertType,
			Portrait:                   cardholder.Portrait,
			ReverseSide:                cardholder.ReverseSide,
			NationalityCountryCode:     cardholder.NationalityCountryCode,
			ResidentialAddress:         cardholder.ResidentialAddress,
			ResidentialCity:            cardholder.ResidentialCity,
			ResidentialCountryCode:     cardholder.ResidentialCountryCode,
			ResidentialPostalCode:      cardholder.ResidentialPostalCode,
			ResidentialState:           cardholder.ResidentialState,
			Status:                     unifiedStatus, // 使用统一状态
			CreatedAt:                  cardholder.CreatedAt,
			UpdatedAt:                  cardholder.UpdatedAt,
			MatrixAccount:              cardholder.MatrixAccount,
			MemberID:                   cardholder.MemberID,
			IsLegal:                    cardholder.IsLegal,
			CardholderReviewStatus:     cardholder.CardholderReviewStatus,
			Reason:                     cardholder.Reason,
		}
		responses = append(responses, response)
	}

	return responses, total, nil
}

// UpdateCardholder 更新持卡人信息
func (s *CardholderService) UpdateCardholder(ctx context.Context, req *models.UpdateHlPayCardholderRequest) (*models.HlPayCardholderResponse, error) {
	// 检查持卡人是否存在
	var cardholder models.HlPayCardholder
	if err := s.db.WithContext(ctx).Where("id = ?", req.ID).First(&cardholder).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("持卡人不存在")
		}
		return nil, fmt.Errorf("查询持卡人失败: %v", err)
	}

	// 验证字段不包含中文（只验证非空字段）
	fieldsToValidate := make(map[string]string)
	if req.FirstName != "" {
		fieldsToValidate["姓名"] = req.FirstName
	}
	if req.LastName != "" {
		fieldsToValidate["姓氏"] = req.LastName
	}
	if req.Email != "" {
		fieldsToValidate["邮箱"] = req.Email
	}
	if req.Mobile != "" {
		fieldsToValidate["手机号"] = req.Mobile
	}
	if req.ResidentialAddress != "" {
		fieldsToValidate["地址"] = req.ResidentialAddress
	}
	if req.ResidentialCity != "" {
		fieldsToValidate["城市"] = req.ResidentialCity
	}
	if req.ResidentialState != "" {
		fieldsToValidate["州/省"] = req.ResidentialState
	}
	if req.ResidentialPostalCode != "" {
		fieldsToValidate["邮编"] = req.ResidentialPostalCode
	}

	if err := common.ValidateMultipleFieldsNoChinese(fieldsToValidate); err != nil {
		return nil, err
	}

	// 移除重复性校验，允许邮箱、手机号、姓名等重复

	// 解析出生日期
	var dateOfBirth *time.Time
	if req.DateOfBirth != "" {
		if parsed, err := time.Parse("2006-01-02", req.DateOfBirth); err == nil {
			dateOfBirth = &parsed
		}
	}

	// 更新字段
	updates := make(map[string]interface{})
	if req.FirstName != "" {
		updates["first_name"] = req.FirstName
	}
	if req.LastName != "" {
		updates["last_name"] = req.LastName
	}
	if req.Email != "" {
		updates["email"] = req.Email
	}
	if req.Mobile != "" {
		updates["mobile"] = req.Mobile
	}
	if req.MobilePrefix != "" {
		updates["mobile_prefix"] = req.MobilePrefix
	}
	if req.CertType != "" {
		updates["cert_type"] = req.CertType
	}
	if req.Portrait != "" {
		updates["portrait"] = req.Portrait
	}
	if req.ReverseSide != "" {
		updates["reverse_side"] = req.ReverseSide
	}
	if req.NationalityCountryCode != "" {
		updates["nationality_country_code"] = req.NationalityCountryCode
	}
	if req.ResidentialAddress != "" {
		updates["residential_address"] = req.ResidentialAddress
	}
	if req.ResidentialCity != "" {
		updates["residential_city"] = req.ResidentialCity
	}
	if req.ResidentialCountryCode != "" {
		updates["residential_country_code"] = req.ResidentialCountryCode
	}
	if req.ResidentialPostalCode != "" {
		updates["residential_postal_code"] = req.ResidentialPostalCode
	}
	if req.ResidentialState != "" {
		updates["residential_state"] = req.ResidentialState
	}
	if req.Status != "" {
		updates["status"] = req.Status
	}
	if dateOfBirth != nil {
		updates["date_of_birth"] = dateOfBirth
	}
	updates["updated_at"] = time.Now()

	// 执行更新
	if err := s.db.WithContext(ctx).Model(&cardholder).Updates(updates).Error; err != nil {
		return nil, fmt.Errorf("更新持卡人失败: %v", err)
	}

	// 返回更新后的详情
	return s.GetCardholderDetail(ctx, req.ID)
}

// DeleteCardholder 删除持卡人
func (s *CardholderService) DeleteCardholder(ctx context.Context, cardholderID int64) error {
	// 检查持卡人是否存在
	var cardholder models.HlPayCardholder
	if err := s.db.WithContext(ctx).Where("id = ?", cardholderID).First(&cardholder).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return fmt.Errorf("持卡人不存在")
		}
		return fmt.Errorf("查询持卡人失败: %v", err)
	}

	// 删除记录
	if err := s.db.WithContext(ctx).Delete(&cardholder).Error; err != nil {
		return fmt.Errorf("删除持卡人失败: %v", err)
	}

	return nil
}

// GetCardholderStats 获取持卡人统计信息
func (s *CardholderService) GetCardholderStats(ctx context.Context) (map[string]interface{}, error) {
	stats := make(map[string]interface{})

	// 统计总持卡人数
	var totalCardholders int64
	if err := s.db.WithContext(ctx).Model(&models.HlPayCardholder{}).Count(&totalCardholders).Error; err != nil {
		return nil, fmt.Errorf("统计总持卡人数失败: %v", err)
	}
	stats["total_cardholders"] = totalCardholders

	// 统计活跃持卡人数
	var activeCardholders int64
	if err := s.db.WithContext(ctx).Model(&models.HlPayCardholder{}).
		Where("status = 'ACTIVE'").
		Count(&activeCardholders).Error; err != nil {
		return nil, fmt.Errorf("统计活跃持卡人数失败: %v", err)
	}
	stats["active_cardholders"] = activeCardholders

	// 统计非活跃持卡人数
	var inactiveCardholders int64
	if err := s.db.WithContext(ctx).Model(&models.HlPayCardholder{}).
		Where("status = 'INACTIVE'").
		Count(&inactiveCardholders).Error; err != nil {
		return nil, fmt.Errorf("统计非活跃持卡人数失败: %v", err)
	}
	stats["inactive_cardholders"] = inactiveCardholders

	// 统计暂停持卡人数
	var suspendedCardholders int64
	if err := s.db.WithContext(ctx).Model(&models.HlPayCardholder{}).
		Where("status = 'SUSPENDED'").
		Count(&suspendedCardholders).Error; err != nil {
		return nil, fmt.Errorf("统计暂停持卡人数失败: %v", err)
	}
	stats["suspended_cardholders"] = suspendedCardholders

	// 统计今日新增持卡人
	var todayNewCardholders int64
	today := time.Now().Format("2006-01-02")
	if err := s.db.WithContext(ctx).Model(&models.HlPayCardholder{}).
		Where("DATE(created_at) = ?", today).
		Count(&todayNewCardholders).Error; err != nil {
		return nil, fmt.Errorf("统计今日新增持卡人失败: %v", err)
	}
	stats["today_new_cardholders"] = todayNewCardholders

	return stats, nil
}

// UpdateCardholderStatus 更新持卡人状态
func (s *CardholderService) UpdateCardholderStatus(ctx context.Context, cardholderID int64, status string) error {
	// 检查持卡人是否存在
	var cardholder models.HlPayCardholder
	if err := s.db.WithContext(ctx).Where("id = ?", cardholderID).First(&cardholder).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return fmt.Errorf("持卡人不存在")
		}
		return fmt.Errorf("查询持卡人失败: %v", err)
	}

	// 更新状态
	if err := s.db.WithContext(ctx).Model(&cardholder).Updates(map[string]interface{}{
		"status":     status,
		"updated_at": time.Now(),
	}).Error; err != nil {
		return fmt.Errorf("更新持卡人状态失败: %v", err)
	}

	return nil
}
